package upload

import (
	"beergo/lib/base/controller"
	"beergo/lib/tool"
	"github.com/beego/beego/v2/server/web"
	"math/rand"
	"strconv"
)

type UploadController struct {
	controller.ContainerController
}

func init() {
	web.Router("/MyWebPicUpload",&UploadController{},"*:MyWebPicUploadAction")
	web.Router("/MyFileUpload",&UploadController{},"*:MyFileUploadAction")
	web.Router("/MyVuePicUpload",&UploadController{},"*:MyVuePicUploadAction")
}

var root string
var serverUrl string

func (this *UploadController) Prepare() {
	rootConf, _ := web.AppConfig.String("Root")
	root = rootConf
	serverUrlConf, _ := web.AppConfig.String("ServerUrl")
	serverUrl = serverUrlConf
}

func (this *UploadController) MyWebPicUploadAction() {
	_, fileInfo, err := this.GetFile("Filedata")
	if err == nil {
		fileTool := tool.FileTool{}
		fileName := fileInfo.Filename
		ext := fileTool.GetExt(fileName)
		targetPath := "/static/upload/" + tool.GetDateYMD() + "/" + tool.GetDateYMDHIS("", "", "") + strconv.Itoa(rand.Intn(9999)) + ext
		this.Try(fileTool.CreateDirForPath(root + targetPath))
		//fullpath,_:=filepath.Abs("."+targetPath)
		fullpath := root + targetPath
		this.HandleErrors(this.SaveToFile("Filedata", fullpath))
		this.JsonOut(1, "OK", targetPath)
	}
	this.JsonOut(0, "上传时发生错误", "")
}

func (this *UploadController) MyFileUploadAction() {
	_, fileInfo, err := this.GetFile("file")
	if err == nil {
		fileTool := tool.FileTool{}
		fileName := fileInfo.Filename
		ext := fileTool.GetExt(fileName)
		targetPath := "/static/upload/" + tool.GetDateYMD() + "/" + tool.GetDateYMDHIS("", "", "") + strconv.Itoa(rand.Intn(9999)) + ext
		this.Try(tool.CreateDirForPath(root + targetPath))
		//fullpath,_:=filepath.Abs("."+targetPath)
		tool.JsonLog(root)
		fullpath := root + targetPath
		this.HandleErrors(this.SaveToFile("file", fullpath))
		this.JsonOut(1, fileName, targetPath)
	}
	this.JsonOut(0, "上传时发生错误", "")
}

func (this *UploadController) MyVuePicUploadAction() {
	_, fileInfo, err := this.GetFile("Filedata")
	if err == nil {
		fileTool := tool.FileTool{}
		fileName := fileInfo.Filename
		ext := fileTool.GetExt(fileName)
		targetPath := "/static/upload/" + tool.GetDateYMD() + "/" + tool.GetDateYMDHIS("", "", "") + strconv.Itoa(rand.Intn(9999)) + ext
		this.Try(fileTool.CreateDirForPath(root + targetPath))
		//fullpath,_:=filepath.Abs("."+targetPath)
		fullpath := root + targetPath
		this.HandleErrors(this.SaveToFile("Filedata", fullpath))
		this.Data["json"] = map[string]interface{}{
			"errno": 0,
			"data":  []string{serverUrl + targetPath},
		}
		this.HandleErrors(this.ServeJSON())
	}
	this.JsonOut(0, "上传时发生错误", this.Ctx.Request)
}
